package com.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.annotation.RateLimit;
import com.boot.constants.RedisKeys;
import com.boot.constants.StatusConstants;
import com.boot.dto.AttachmentDTO;
import com.boot.dto.QuestionDetailDTO;
import com.boot.dto.UserSummaryDTO;
import com.boot.entity.Attachment;
import com.boot.entity.Question;
import com.boot.entity.QuestionAssignment;
import com.boot.entity.User;
import com.boot.mapper.QuestionAssignmentMapper;
import com.boot.service.IAttachmentService;
import com.boot.service.IQuestionService;
import com.boot.service.IUserService;
import com.boot.service.MailService;
import com.boot.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/question")
@Slf4j
public class QuestionController {

    @Resource
    private IQuestionService questionService;

    @Resource
    private QuestionAssignmentMapper assignmentMapper;

    @Resource
    private IAttachmentService attachmentService;

    @Resource
    private IUserService userService;

    @Resource
    private MailService mailService;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @RateLimit(limit = 20, windowSec = 60)
    // 查询所有待审批的问题（分页）
    @GetMapping("/pending-review")
    public R<IPage<Question>> getPendingReviewQuestions(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Page<Question> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Question> wrapper = new QueryWrapper<Question>()
                .in("status", StatusConstants.QuestionStatus.PENDING_REVIEW, StatusConstants.QuestionStatus.AWAITING_ADMIN)
                .orderByDesc("created_at"); // 按创建时间倒序

        IPage<Question> result = questionService.page(page, wrapper);
        return R.page(result);
    }

    @RateLimit(limit = 20, windowSec = 60)
    // 审批通过
    @PostMapping("/{id}/approve")
    public R<Void> approveQuestion(@PathVariable Long id, @RequestParam(required = false) String reviewNotes) {
        Question question = questionService.getById(id);
        if (question == null) {
            return R.error("问题不存在");
        }

        if (!StatusConstants.QuestionStatus.PENDING_REVIEW.equals(question.getStatus()) && !StatusConstants.QuestionStatus.AWAITING_ADMIN.equals(question.getStatus())) {
            return R.error("该问题当前不可审批");
        }

        // 获取提问用户信息用于发邮件
        User submitter = userService.getById(question.getUserId());
        if (submitter == null) {
            log.warn("无法找到问题 {} 的提交者信息", id);
            return R.error("用户不存在");
        }

        if (submitter.getStatus().equals(StatusConstants.UserStatus.DISABLED)) {
            return R.error("无法发送邮件：用户已被禁用");
        }

        UpdateWrapper<Question> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("status", StatusConstants.QuestionStatus.WAITING)
                .set("reviewed_at", LocalDateTime.now())
                .set("review_notes", reviewNotes);

        boolean updated = questionService.update(wrapper);

        // 发送审批通过邮件
        if (updated && submitter != null && submitter.getEmail() != null && !submitter.getEmail().trim().isEmpty()) {
            try {
                String subject = "您的问题已通过审批";
                String content = buildApprovedEmail(submitter.getUsername(), question.getTitle());
                mailService.sendHtmlMail(submitter.getEmail(), subject, content);

                // 已处理，去除redis中记录的问题
                redisTemplate.opsForSet().remove(RedisKeys.SENT_QUESTION_NOTIFY, String.valueOf(id));
            } catch (Exception e) {
                log.error("【邮件发送失败】问题审批通过通知: 邮箱={} , 错误: {}", submitter.getEmail(), e.getMessage(), e);
            }
        }

        return updated ? R.success(null) : R.error("审批失败");
    }

    @RateLimit(limit = 20, windowSec = 60)
    // 审批不通过
    @PostMapping("/{id}/reject")
    public R<Void> rejectQuestion(@PathVariable Long id, @RequestParam String reviewNotes) {
        if (reviewNotes == null || reviewNotes.trim().isEmpty()) {
            return R.error("请填写驳回原因");
        }

        Question question = questionService.getById(id);
        if (question == null) {
            return R.error("问题不存在");
        }

        if (!StatusConstants.QuestionStatus.PENDING_REVIEW.equals(question.getStatus()) && !StatusConstants.QuestionStatus.AWAITING_ADMIN.equals(question.getStatus())) {
            return R.error("该问题当前不可驳回");
        }

        // 获取提问用户信息用于发邮件
        User submitter = userService.getById(question.getUserId());
        if (submitter == null) {
            log.warn("无法找到问题 {} 的提交者信息", id);
            return R.error("用户不存在");
        }

        if (submitter.getStatus().equals(StatusConstants.UserStatus.DISABLED)) {
            return R.error("无法发送邮件：用户已被禁用");
        }

        UpdateWrapper<Question> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("status", StatusConstants.QuestionStatus.REJECTED)
                .set("reviewed_at", LocalDateTime.now())
                .set("review_notes", reviewNotes);

        boolean updated = questionService.update(wrapper);

        // 发送驳回通知邮件
        if (updated && submitter != null && submitter.getEmail() != null && !submitter.getEmail().trim().isEmpty()) {
            try {
                String subject = "您的问题未通过审批";
                String content = buildRejectedEmail(submitter.getUsername(), question.getTitle(), reviewNotes);
                mailService.sendHtmlMail(submitter.getEmail(), subject, content);

                // 已处理，去除redis中记录的问题
                redisTemplate.opsForSet().remove(RedisKeys.SENT_QUESTION_NOTIFY, String.valueOf(id));
            } catch (Exception e) {
                log.error("【邮件发送失败】问题驳回通知: 邮箱={} , 错误: {}", submitter.getEmail(), e.getMessage(), e);
            }
        }

        return updated ? R.success(null) : R.error("驳回失败");
    }

    @RateLimit(limit = 20, windowSec = 60)
    // 根据 ID 获取问题详情
    @GetMapping("/{id}")
    public R<QuestionDetailDTO> getQuestionDetail(@PathVariable Long id) {
        try {
            Question question = questionService.getById(id);
            if (question == null) {
                return R.error("问题不存在");
            }

            QuestionDetailDTO dto = new QuestionDetailDTO();
            dto.setId(question.getId());
            dto.setTitle(question.getTitle());
            dto.setType(question.getType());
            dto.setDescription(question.getDescription());
            dto.setExpected(question.getExpected());
            dto.setStatus(question.getStatus());
            dto.setCreatedAt(question.getCreatedAt());
            dto.setResolvedAt(question.getResolvedAt());

            // 查询附件
            List<Attachment> attachments = attachmentService.listAttachmentsByQuestionId(id);
            List<AttachmentDTO> attachmentDTOS = attachments.stream().map(att -> {
                AttachmentDTO adto = new AttachmentDTO();
                adto.setId(att.getId());
                adto.setName(att.getFileName());
                adto.setSizeKb(att.getSizeKb());
                adto.setMimeType(att.getMimeType());
                adto.setCreatedAt(att.getCreatedAt());
                return adto;
            }).collect(Collectors.toList());

            dto.setAttachments(attachmentDTOS);

            // =================== 新增：查询待处理专家列表 ===================
            // 获取所有该问题下的专家 assignment 记录
            List<QuestionAssignment> pendingAssignments = assignmentMapper.selectList(
                    new QueryWrapper<QuestionAssignment>()
                            .eq("question_id", id)
            );

            if (!pendingAssignments.isEmpty()) {
                // 提取 expertId 列表
                List<Long> expertIds = pendingAssignments.stream()
                        .map(QuestionAssignment::getExpertId)
                        .collect(Collectors.toList());

                // 查询这些专家的基本信息（只选 id 和 username）
                List<User> experts = userService.list(
                        new QueryWrapper<User>()
                                .in("id", expertIds)
                                .select("id", "username")  // 关键：避免查出 password
                );

                // 转换为 DTO
                List<UserSummaryDTO> pendingExperts = experts.stream().map(u -> {
                    UserSummaryDTO summary = new UserSummaryDTO();
                    summary.setId(u.getId());
                    summary.setUsername(u.getUsername());
                    return summary;
                }).collect(Collectors.toList());

                dto.setPendingExperts(pendingExperts);
            } else {
                dto.setPendingExperts(Collections.emptyList());
            }

            return R.success(dto);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.error("系统错误");
        }
    }

    // 构建审批通过邮件内容
    private String buildApprovedEmail(String username, String questionTitle) {
        return "<div style='font-family: Arial, sans-serif; padding: 20px; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto;'>"
                    + "<h2 style='color: #4CAF50;'>✅ 问题已通过审批</h2>"
                    + "<p><strong>您好，" + username + "：</strong></p>"
                    + "<p>您提交的问题已通过审核，即将进入处理流程。</p>"
                    + "<table style='width:100%; border-collapse: collapse; margin: 20px 0;'>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ccc; width: 30%;'><strong>问题标题</strong></td>"
                        + "<td style='padding: 8px; border: 1px solid #ccc;'>" + questionTitle + "</td></tr>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ccc;'><strong>状态更新</strong></td>"
                        + "<td style='padding: 8px; border: 1px solid #ccc; color: green; font-weight: bold;'>已通过审批</td></tr>"
                    + "</table>"
                    + "<p>我们将尽快安排专家为您处理，感谢您的耐心等待！</p>"
                    + "<footer style='margin-top: 30px; color: #777; font-size: 0.9em; text-align: center;'>"
                    + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台</footer>"
                + "</div>";
    }

    // 构建驳回邮件内容
    private String buildRejectedEmail(String username, String questionTitle, String reason) {
        return "<div style='font-family: Arial, sans-serif; padding: 20px; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto;'>"
                    + "<h2 style='color: #f44336;'>❌ 问题未通过审批</h2>"
                    + "<p><strong>尊敬的 " + username + "：</strong></p>"
                    + "<p>您提交的问题未能通过审核，具体信息如下：</p>"
                    + "<table style='width:100%; border-collapse: collapse; margin: 20px 0;'>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ccc; width: 30%;'><strong>问题标题</strong></td>"
                        + "<td style='padding: 8px; border: 1px solid #ccc;'>" + questionTitle + "</td></tr>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ccc;'><strong>审核结果</strong></td>"
                        + "<td style='padding: 8px; border: 1px solid #ccc; color: red; font-weight: bold;'>已驳回</td></tr>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ccc;'><strong>驳回原因</strong></td>"
                        + "<td style='padding: 8px; border: 1px solid #ccc;'>" + reason + "</td></tr>"
                    + "</table>"
                    + "<p>请根据反馈修改后重新提交。如有疑问，请联系管理员。</p>"
                    + "<footer style='margin-top: 30px; color: #777; font-size: 0.9em; text-align: center;'>"
                    + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台</footer>"
                + "</div>";
    }
}
